package com.cos.blog.core.controller;


import com.cos.blog.core.servlet.BaseServlet;
import com.cos.blog.entity.UserEntity;
import com.cos.blog.services.IUserService;
import com.cos.blog.services.impl.UserServiceImpl;
import org.apache.commons.io.IOUtils;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Part;
import java.io.FileInputStream;

@WebServlet("/FileServlet/*")
@MultipartConfig
public class FileServlet extends BaseServlet {

    private IUserService userService = new UserServiceImpl();

    public String upload() throws Exception {
        // 1.获取前端传递的二进制文件
        Part part = req.getPart("pngFile");
        // 2.获取文件名称
        String fileName = part.getSubmittedFileName();
        // 3.获取文件上传的位置
        String pngPath = req.getServletContext().getRealPath("png");
        System.out.println("pngPath:"+pngPath);
        // 4.文件的路径
        String filePath = pngPath + "\\" + fileName;
//        part.write(pngPath + "\\" + fileName);
//        System.out.println(filePath);
        // 5.把文件写入到指定位置
        part.write(filePath);
        // 6.更新用户头像地址
        UserEntity loginUser = (UserEntity) req.getSession().getAttribute("loginUser");
        userService.updateHeaderUrl(loginUser.getId(), filePath);
        return outJson(true);
    }

    /**
     * @Author:zxc
     * @Description: 截取图片的名称路径访问   本地的图片
     */
    public void showPng() throws Exception {
        String url = req.getParameter("fileName");
        String png = req.getServletContext().getRealPath("png");
        FileInputStream ips = new FileInputStream(png + "//" + url);
        // IO流拷贝，把ips中的内容拷贝ops中
        IOUtils.copy(ips, resp.getOutputStream());
    }
}
